#!/bin/sh

while true

do

i=0

#手动输入一个数字

read -p "请输入1~100之间的一个数字：" Random_Num

if [[ ! ( $Random_Num =~ ^[0-9]+$ && $Random_Num -ge 1 && $Random_Num -le 100 ) ]];then

echo "输入的数字不在1~100之间，请重新输入!!!"

continue

fi

# 进行二分法查找输入的数字

array=(`seq 100 | tr '\n' ' ' | sed -nr 's#(.*)100 #\1100\n#gp'`)

front=0

end=$[ ${#array[*]} - 1 ]

middle=`awk "BEGIN{print (${front} + ${end})/2}"`

while [ $front -le $end ]

do

let i++

middle=`awk "BEGIN{print (${front} + ${end})/2}"`

# echo "第 $i 次数组下标middle为：${middle%.*} 下标middle所对应的值为：$[ ${middle%.*} + 1 ]"

if [ $Random_Num -eq ${array[${middle%.*}]} ];then

echo "二分法查询的次数为：$i"

echo "二分法查询的结果为：${array[${middle%.*}]}"

break

fi

if [ $Random_Num -gt ${array[${middle%.*}]} ];then

front=$[ ${middle%.*} + 1 ]

#echo "front的值为：$front "

fi

if [ $Random_Num -lt ${array[${middle%.*}]} ];then

end=$[ ${middle%.*} - 1 ]

#echo "end的值为：$end "

fi

done

done

#!/bin/sh

# 用随机数产生一个数字

Random_Num=`echo $((RANDOM%100+1))`

echo "RANDOM产生随机数的值为 $Random_Num "

# 进行二分法查找输入的数字

array=(`seq 100 | tr '\n' ' ' | sed -nr 's#(.*)100 #\1100\n#gp'`)

front=0

end=$[ ${#array[*]} - 1 ]

middle=`awk "BEGIN{print (${front} + ${end})/2}"`

while [ $front -le $end ]

do

let i++

middle=`awk "BEGIN{print (${front} + ${end})/2}"`

# echo "第 $i 次数组下标middle为：${middle%.*} 下标middle所对应的值为：$[ ${middle%.*} + 1 ]"

if [ $Random_Num -eq ${array[${middle%.*}]} ];then

echo "二分法查询的次数为：$i 次"

echo "二分法查询的结果为：${array[${middle%.*}]} "

break

fi

if [ $Random_Num -gt ${array[${middle%.*}]} ];then

front=$[ ${middle%.*} + 1 ]

#echo "front的值为：$front "

fi

if [ $Random_Num -lt ${array[${middle%.*}]} ];then

end=$[ ${middle%.*} - 1 ]

#echo "end的值为：$end "

fi

done